package com.kx.game.center.servlet;

import com.kx.core.dawn.dbs.dao.DaoManager;
import com.kx.core.dawn.dbs.entity.GameServerEntity;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.common.ServerEnum;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 同步数据 登录人数5分钟一次
 */
@WebServlet(urlPatterns = "/syncServerInfo", asyncSupported = true)
public class SyncInfoServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(SyncInfoServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            GSServices.loadManager.redisState();
            String serverId = request.getParameter("serverId");
            String loginNum = request.getParameter("loginNum");
            String createNum = request.getParameter("createNum");
            String serverState = request.getParameter("serverState");
            if (serverState == null || serverState.equals("")) {
                serverState = ServerEnum.START.getIndex() + "";
            }
            //DB更新
            GameServerEntity gameServerEntity = DaoManager.gameServerDao.get(serverId);
            gameServerEntity.setLoginNum(Integer.valueOf(loginNum));
            gameServerEntity.setCreateNum(Integer.valueOf(createNum));
            gameServerEntity.setState(serverState);
            DaoManager.gameServerDao.update(gameServerEntity);
//            GSServices.redisManager.getRedisTemplate().multi();
            //登录数量
            GSServices.localManager.updateGSLoginCount(serverId, Integer.valueOf(loginNum));
            //创建数量
            GSServices.localManager.updateServerCreateNum(serverId, Integer.valueOf(createNum));
            //服务器状态
            GSServices.localManager.updateGameServerState(serverId, ServerEnum.indexOf(Integer.valueOf(serverState)));
//            GSServices.redisManager.getRedisTemplate().exec();
            GSServices.gameManager.printLog(request, logger, "数据同步");
            GSServices.localManager.sendMessage(response, true, null, "");
        } catch (Exception e) {
            e.printStackTrace();
            GSServices.localManager.sendMessage(response, false, LocalErrorResponseCode.SYSTEM_ERROR, "");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
